package com.woniu.service.impl;

import com.woniu.dao.*;
import com.woniu.pojo.*;
import com.woniu.service.PermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private StudentDao studentDao;
    @Resource
    private ClazzDao clazzDao;
    @Resource
    private JobDao jobDao;
    @Resource
    private RoleDao roleDao;
    @Resource
    private PermissionDao permissionDao;
    @Resource
    private RolepermissionDao rolepermissionDao;

    /**
     * 学生男女比例(每班 或 所有)
     * @param cid
     * @return
     */
    @Override
    public Clazz ratio(Integer cid) {
        Clazz clazz = new Clazz();
        StudentExample studentExample = new StudentExample();
        StudentExample.Criteria criteria = studentExample.createCriteria();
        //为空时，查所有学生
        if(cid != -1){
            criteria.andCidEqualTo(cid);
        }
        //查询男女的人
        List<Student> students1 = studentDao.selectByExample(studentExample);
        criteria.andSexEqualTo("男");
        //查询男生的人
        List<Student> students2 = studentDao.selectByExample(studentExample);
        if(cid == -1) {
            //设置班级名为全校区
            clazz.setCname("全校区");
        }else {
            //查询班级
            Clazz clazz1 = clazzDao.selectByPrimaryKey(cid-1);
            clazz.setCname(clazz1.getCname());
        }
        //设置男女人数
        clazz.setBoy(students2.size());
        clazz.setGril(students1.size()-students2.size());
        //返回
        return clazz;
    }

    /**
     * 查询所有的班级的比例
     * @return
     */
    @Override
    public List<Clazz> radioAll() {
        List<Clazz> clazzList = new ArrayList<>();
        //获取所有的班级
        ClazzExample clazzExample = new ClazzExample();
        clazzExample.createCriteria().andCstateEqualTo("已结课");
        List<Clazz> clazzes = clazzDao.selectByExample(clazzExample);
        //遍历每个班级对应的男女人数
        for(int i = 0;i<clazzes.size();i++){
            //获取这个班对象
            Clazz clazz = clazzes.get(i);
            //查询条件
            StudentExample studentExample = new StudentExample();
            StudentExample.Criteria criteria = studentExample.createCriteria();
            criteria.andCidEqualTo(clazzes.get(i).getCid());
            //查询出总人数
            List<Student> students1 = studentDao.selectByExample(studentExample);
            criteria.andSexEqualTo("男");
            //查询出男生人数
            List<Student> students2 = studentDao.selectByExample(studentExample);
            clazz.setBoy(students2.size());
            clazz.setGril(students1.size()-students2.size());
            clazzList.add(clazz);
        }
        return clazzList;
    }

    @Override
    public List<ResourceVO> radioresource(Integer cid) {
        List<ResourceVO> studentList = new ArrayList<>();
        //获取所有的来源
        StudentExample studentExample1 = new StudentExample();
        StudentExample.Criteria criteria1 = studentExample1.createCriteria();
        //为空时，查所有学生
        if(cid != -1){
            criteria1.andCidEqualTo(cid);
        }
        List<Student> students = studentDao.selectByExample(studentExample1);
        //保存所有的学生来源
        Map<String,Integer> resource = new HashMap<>();
        for (Student student:students) {
            if(resource.get(student.getResource())!=null){
                resource.put(student.getResource(), resource.get(student.getResource())+1);
            }else {
                resource.put(student.getResource(), 1);
            }
        }
        Set<Map.Entry<String, Integer>> entries = resource.entrySet();
        for(Map.Entry<String, Integer> key:entries){
            ResourceVO resourceVO = new ResourceVO();
            resourceVO.setResource(key.getKey());
            resourceVO.setCount(key.getValue());
            studentList.add(resourceVO);
        }
        return studentList;
    }

    /**
     * 查询所有地区就业的工资
     * @return
     */
    @Override
    public List<Job> salary(String cid, Date begin, Date end) {
        JobExample jobExample = new JobExample();
        JobExample.Criteria criteria = jobExample.createCriteria();

//        //根据毕业日期查询满足条件的班级
        ClazzExample clazzExample = new ClazzExample();
        ClazzExample.Criteria criteria2 = clazzExample.createCriteria();
        if(begin != null && !("".equals(begin))){
            criteria2.andEndGreaterThanOrEqualTo(begin);
        }
        if(end != null && !("".equals(end))){
            criteria2.andEndLessThanOrEqualTo(end);
        }
        criteria2.andCstateEqualTo("已结课");
        List<Clazz> clazzList = clazzDao.selectByExample(clazzExample);
        List<Integer> cidList2 = new ArrayList<>();
        for (Clazz calzz: clazzList
        ) {
            cidList2.add(calzz.getCid());
        }
        //根据cid查sid
        List<Integer> sidList3 = null ;
        if(cidList2.size()>0) {
            StudentExample studentExample3 = new StudentExample();
            StudentExample.Criteria criteria3 = studentExample3.createCriteria();
            criteria3.andCidIn(cidList2);
            List<Student> students3 = studentDao.selectByExample(studentExample3);
            sidList3 = new ArrayList<>();
            for (int i = 0; i < students3.size(); i++) {
                sidList3.add(students3.get(i).getSid());
            }
        }
        //为空判断
        if(cid != null && !cid.equals("") && !cid.equals("null")){
            //查询这个班对应的学生id
            StudentExample studentExample = new StudentExample();
            StudentExample.Criteria criteria1 = studentExample.createCriteria();
            criteria1.andCidEqualTo(Integer.parseInt(cid));
            List<Student> students = studentDao.selectByExample(studentExample);
            List<Integer> sidList = new ArrayList<>();
            for(int i = 0 ;i<students.size();i++){
                if(cidList2.size()>0 && cidList2.contains(Integer.parseInt(cid))) {
                    sidList.add(students.get(i).getSid());
                }else if(cidList2.size() == 0 && ((begin != null && !("".equals(begin))) || (end != null && !("".equals(end))))){
                    break;
                }
                else {
                    break;
                }
            }
            //设置查询条件
            if(sidList.size()>0) {
                criteria.andSidIn(sidList);
            }else {
                criteria.andSidEqualTo(-1);
            }
        }else {
            if(cidList2.size()>0) {
                criteria.andSidIn(sidList3);
            }else if(cidList2.size() == 0 && ((begin != null && !("".equals(begin))) || (end != null && !("".equals(end))))){
                criteria.andSidEqualTo(-1);
            }
        }
        //按照条件查询
        List<Job> jobs = jobDao.selectByExample(jobExample);
        //保存地区和总工资
        Map<String,Double> map = new HashMap<>();
        //保存地区和人数
        Map<String,Double> map2 = new HashMap<>();
        for(int i = 0 ;i<jobs.size();i++){
            if(map.get(jobs.get(i).getLoc()) != null){
                Double parm = map.get(jobs.get(i).getLoc());
                Double parm2 = jobs.get(i).getSalary();
                Double parm3 = parm+parm2;
//                map.put(jobs.get(i).getLoc(),map.get(jobs.get(i).getLoc())+jobs.get(i).getSalary());
                map.put(jobs.get(i).getLoc(),parm3);
                Double parm4 = map2.get(jobs.get(i).getLoc());
                Double parm5 = parm4+1;
                map2.put(jobs.get(i).getLoc(),parm5);
            }else {
                map.put(jobs.get(i).getLoc(), jobs.get(i).getSalary());
                map2.put(jobs.get(i).getLoc(), 1.0);
            }
        }
        //保存地区和平均工资  和地区工作总人数
        List<Job> jobList = new ArrayList<>();
        //计算地区的平均工资
        Set<Map.Entry<String, Double>> entries = map.entrySet();
        for(Map.Entry<String, Double> key:entries){
            String loc = key.getKey();
            //获取这个key对应的总月薪
            Double salary = key.getValue();
            //获取这个key对应的总人数
            Double count = map2.get(loc);
            //计算这个key对应的平均工资
            Double avsalary = (int)(salary/count*100)/100.0;
            //生产一个job对象，保存在jobList中
            Job job = new Job();
            job.setLoc(loc);job.setAvsalary(avsalary);job.setCount(count.intValue());
            jobList.add(job);
        }
        return jobList;
    }

    /**
     * 列表展示页面分页查询
     * @param pageBean
     * @param cid
     * @param stname
     * @param sid
     * @return
     */
    @Override
    public Map<String, Object>  findByConf(PageBean pageBean, Integer cid, String stname,String sid) {
        JobExample jobExample = new JobExample();
        JobExample.Criteria criteria = jobExample.createCriteria();

        //获取这个班所有的uid
        StudentExample studentExample = new StudentExample();
        StudentExample.Criteria criteria1 = studentExample.createCriteria();
        if(cid != null && !cid.equals("")){
            criteria1.andCidEqualTo(cid);
        }
        if(stname != null && !stname.equals("")){
            criteria1.andStnameLike("%"+stname+"%");
        }

        List<Student> students = studentDao.selectByExample(studentExample);
        List<Integer> sidList = new ArrayList<>();
        for(int i = 0 ;i<students.size();i++){
            sidList.add(students.get(i).getSid());
        }

        if(sid != null && !sid.equals("")){
            int parm = Integer.parseInt(sid);
            if(sidList.size()>0 && !(sidList.contains(parm))){
                criteria.andSidEqualTo(-1);
            }else if(sidList.size() == 0 && stname != null && !stname.equals("")){
                criteria.andSidEqualTo(-1);
            }else{
                criteria.andSidEqualTo(parm);
            }
        }else{
            if(sidList.size()>0){
                criteria.andSidIn(sidList);
            }else if(sidList.size() == 0 && stname != null && !stname.equals("")){
                criteria.andSidEqualTo(-1);
            }
        }
        //分页查询
        long countRow= jobDao.countByExample(jobExample);
        pageBean.setCountRow((int)countRow);
        Integer countPage=pageBean.getCountRow()%pageBean.getPageSize()==0?pageBean.getCountRow()/pageBean.getPageSize():pageBean.getCountRow()/pageBean.getPageSize()+1;
        pageBean.setCountPage(countPage);
        jobExample.setOffset((long)((pageBean.getCurrentPage()-1)*pageBean.getPageSize()));
        jobExample.setLimit(pageBean.getPageSize());

        //倒序查找
        jobExample.setOrderByClause("jid DESC");
        List<Job> jobList = jobDao.selectByExample(jobExample);
        Map<String, Object> map = new HashMap<>();
        map.put("jobList",jobList);
        map.put("pageBean",pageBean);

        return map;
    }
    /**
     * 删除一个毕业生信息
     * @param jid
     * @return
     */
    @Override
    public int deleteone(Integer jid) {
        int i = jobDao.deleteByPrimaryKey(jid);
        return i;
    }


    @Override
    public int deletemany(Integer[] jid) {
        JobExample jobExample = new JobExample();
        JobExample.Criteria criteria = jobExample.createCriteria();
        criteria.andJidIn(Arrays.asList(jid.clone()));
        int i = jobDao.deleteByExample(jobExample);
        return i;
    }
    /**
     * 增加一个毕业生信息
     * @param
     * @return
     */
    @Override
    public int savebeyeInfo(Integer cid, String sid, String salary, String loc) {
        //通过cid 和 sid 判断有没有这个人
        StudentExample studentExample = new StudentExample();
        StudentExample.Criteria criteria = studentExample.createCriteria();
        criteria.andCidEqualTo(cid);
        criteria.andSidEqualTo(Integer.parseInt(sid));
        List<Student> students = studentDao.selectByExample(studentExample);
        if(students.size() == 0 ){
            return -1;
        }

        Job job = new Job();
        job.setSid(students.get(0).getSid());
        job.setSalary(Double.parseDouble(salary));
        job.setLoc(loc);
        int i = jobDao.insertSelective(job);
        return i;
    }
    /**
     * 展示一个毕业生信息（修改）
     * @param
     * @return
     */
    @Override
    public Job updateshow(Integer jid) {
        Job job = jobDao.selectByPrimaryKey(jid);
        Student student = studentDao.selectByPrimaryKey(job.getSid());
        job.setStudent(student);
        return job;
    }
    /**
     * 修改一个毕业生信息
     */
    @Override
    public int updatebeyeInfo(Job job) {
        int i = jobDao.updateByPrimaryKeySelective(job);
        return i;
    }

    /**
     * 查看所有的角色(不包含管理员)
     * @return
     */
    @Override
    public List<Role> findAll() {
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
         criteria.andSoftdelNotEqualTo("0");
        List<Role> roles = roleDao.selectByExample(roleExample);
        return roles;
    }

    /**
     * 查询对应rid的权限
     * @param rid
     * @return
     */
    @Override
    public Map<String, Object> find(String rid) {

        //通过rid 获取 pid
        RolepermissionExample rolepermissionExample = new RolepermissionExample();
        List<Integer> pidList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        if(rid != null && !rid.equals("") && Integer.parseInt(rid)!=-1 && !rid.equals("undefined")){
            RolepermissionExample.Criteria criteria = rolepermissionExample.createCriteria();
            criteria.andRidEqualTo(Integer.parseInt(rid));
            List<Rolepermission> rolepermissions = rolepermissionDao.selectByExample(rolepermissionExample);
            //防止每个角色都什么权限都没有
            if(rolepermissions.size() == 0){
                //获取所有
                PermissionExample permissionExample = new PermissionExample();
                permissionExample.createCriteria().andParentidNotEqualTo(0);
                List<Permission> permissionList2 = permissionDao.selectByExample(permissionExample);
                map.put("unassignperissionList",null);
                map.put("assignpermissionList",permissionList2);
                return map;
            }
            pidList = new ArrayList<>();
            for(int i = 0 ;i<rolepermissions.size();i++) {
                pidList.add(rolepermissions.get(i).getPid());
            }
        }else {
            //获取所有
            PermissionExample permissionExample = new PermissionExample();
            permissionExample.createCriteria().andParentidNotEqualTo(0);
            List<Permission> permissionList2 = permissionDao.selectByExample(permissionExample);
            map.put("unassignperissionList",permissionList2);
            map.put("assignpermissionList",null);
            return map;
        }

        //通过pid 查 已有的permission
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria criteria2 = permissionExample.createCriteria();
        if(pidList.size() == 0){
            criteria2.andPidEqualTo(-1);
        }else {
            criteria2.andPidIn(pidList);
        }
        criteria2.andParentidNotEqualTo(0);
        List<Permission> permissionList = permissionDao.selectByExample(permissionExample);

        PermissionExample permissionExample3 = new PermissionExample();
//        if(pidList.size() == 0){
        PermissionExample.Criteria criteria = permissionExample3.createCriteria();
        criteria.andPidNotIn(pidList);
//        }else {
//            permissionExample2.createCriteria().andPidEqualTo(-1);
//        }
        criteria.andParentidNotEqualTo(0);
        List<Permission> permissionList3 = permissionDao.selectByExample(permissionExample3);
        map.put("unassignperissionList",permissionList);
        map.put("assignpermissionList",permissionList3);
        return map;
    }
}

